<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-10-15
 * Time: 下午3:18
 * 使用邮箱注册，短信验证码要钱的啊.....
 */
namespace Api\Home;

use Common\HttpStatus;
use Common\PlutoApi;
use Common\Request;
use Common\RequestApi;
use Common\Response;
use Common\ResponseApi;
use DB\Home\AccountUser;
use DB\Home\AccountUserInfo;
use DB\VerifyCode;

class BuildAccountRequest extends RequestApi {
  /**
   * @var string
   */
  public $email;
  /**
   * @var int
   */
  public $code;
}

class BuildAccountResponse extends ResponseApi {
  /**
   * @var string 用户id
   */
  public $uid;
  public $message;
  public $password;
}

class BuildAccount extends PlutoApi{
  protected function run(Request $request, Response $response) {
    /**
     * @var $rqData BuildAccountRequest
     */
    $rqData = $request->data;
    if (empty($rqData->email) || filter_var($rqData->email,FILTER_VALIDATE_EMAIL) == false){
      $response->httpStatus = HttpStatus::PARAMETER_ERROR;
      $response->httpMessage = "email is not set or type is error";
      return;
    }
    if (empty($rqData->code)){
      $response->httpStatus = HttpStatus::PARAMETER_ERROR;
      $response->httpMessage = "code is not set";
      return;
    }
    $verify = new VerifyCode();
    if(!$verify->validate($rqData->email,$rqData->code)){
      $response->httpStatus = HttpStatus::Forbidden;
      $response->httpMessage = "verifyCode is error";
      return;
    }
    $user = new AccountUser();
    $info = new AccountUserInfo();
    $info->email = $rqData->email;
    $initPwd = $user->initPwd($rqData->email);
    $info->password = $user->encryPassword($initPwd);
    if(($uid = $user->insert($info)) == null){
      $response->httpStatus = HttpStatus::ERROR;
      $response->httpMessage = "insert failed";
      return;
    }
    $response->data = new BuildAccountResponse();
    $response->data->uid = $uid;
    $response->data->password = $initPwd;
    $response->data->message = "注册成功";

  }
}